package logger

import (
	"errors"
	"io/ioutil"
	"log"
	"os"
	"strings"
	"time"
)

type FileManager struct {
	filePath string
	//多久时间轮转文件
	rotateDuration int64
	expireDuration int64
}

func NewFileManager(f string, duration, exDuration int64) *FileManager {
	return &FileManager{
		filePath:       f,
		rotateDuration: duration,
		expireDuration: exDuration,
	}
}

func (f *FileManager) Rotate() {
	Rotate()
}

func (f *FileManager) RemoveExpireFile() {
	logDir, err := f.getDirFromPath(f.filePath)
	if err != nil {
		log.Println("日志目录解析异常")
		return
	}

	fileList, err := ioutil.ReadDir(logDir)
	if err != nil {
		log.Println("日志文件扫描失败：", err)
		return
	}

	for _, file := range fileList {
		if file.IsDir() || !strings.HasPrefix(file.Name(), filePrefix) {
			continue
		}
		if (time.Now().Unix() - file.ModTime().Unix()) > f.expireDuration*60 {
			oldFilePath := logDir + "/" + file.Name()
			if err := os.Remove(oldFilePath); err != nil {
				log.Println("日志文件删除失败:", oldFilePath, err)
			}
		}
	}
}

func (f *FileManager) getDirFromPath(filePath string) (string, error) {
	if filePath == "" {
		log.Println("日志文件路径为空，日志路径解析失败")
		return "", errors.New("日志文件路径为空")
	}
	pathArr := strings.Split(filePath, "/")
	if pathArr == nil || len(pathArr) < 2 {
		return "", errors.New("日志文件路径解析失败")
	}
	pathArr = pathArr[:len(pathArr)-1]
	return strings.Join(pathArr, "/"), nil
}
